# https://gitee.com/yueyinqiu5990/tj12413601/blob/master/assignment1/question1/main_integration.py
import random

import monte_carlo


def _main():
    random.seed(1234)

    def integrand(x: float):
        return x ** 2

    expected = 1 / 3
    end_condition = float(input(
        "请输入终止条件，如 1e-5 （当“与上一结果相差”和“与理论值相差”均小于它时将终止）："))

    print("|针数|结果|与上一结果相差|与理论值相差|")
    print("|:-:|:-:|:-:|:-:|")
    needle_count = 20
    actual = monte_carlo.integrate_1d_from_0_to_1(integrand, needle_count)
    print(f"|{needle_count}|"
          f"{actual:.3e}|"
          f"-|"
          f"{actual - expected:.3e} ({(actual - expected) / expected * 100:.2f}%)|")
    while True:
        new_actual = actual
        new_actual += monte_carlo.integrate_1d_from_0_to_1(integrand, needle_count)
        new_actual /= 2

        needle_count *= 2
        actual_difference = new_actual - actual
        expected_difference = new_actual - expected
        print(f"|{needle_count}|"
              f"{actual:.3e}|"
              f"{actual_difference:.3e}|"
              f"{expected_difference:.3e} ({expected_difference / expected * 100:.2f}%)|")
        if abs(actual_difference) < end_condition and abs(expected_difference) < end_condition:
            return
        actual = new_actual


if __name__ == "__main__":
    _main()
